package book;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockInterruptiblyTest{

	ReentrantLock lock = new ReentrantLock();
	Condition condition = lock.newCondition();
	
	public void waitMethod(){
		
		try{
//			lock.lock();
			lock.lockInterruptibly();
			System.out.println("lock begin " + Thread.currentThread().getName());
			for(int i = 0; i < Integer.MAX_VALUE; i++){
				
				String newString = new String();
			}
			System.out.println("lock end " + Thread.currentThread().getName());
		} catch (InterruptedException e) {
			System.out.println(Thread.currentThread().getName() + "出现异常");
			e.printStackTrace();
		}finally{
			if(lock.isHeldByCurrentThread()){
				
				lock.unlock();
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		
		final ReentrantLockInterruptiblyTest lockTask = new ReentrantLockInterruptiblyTest();
		Runnable run = new Runnable() {
			
			@Override
			public void run() {
				lockTask.waitMethod();
			}
		};
		
		Thread t = new Thread(run, "A");
		t.start();
		
		Thread.sleep(500);
		Thread t2 = new Thread(run, "B");
		t2.start();
		t2.interrupt();
		
		System.out.println("main end");
	}
}
